package com.company.utils;

import org.apache.commons.lang.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by jiayazi on 17/8/1.
 */
public class TimeTools {

    /**
     * str转date
     * @param dateStr
     * @param pattern  如  yyyy-MM-dd
     * @return
     */
    public static Date formatToDate(String dateStr,String pattern) {
        if (StringUtils.isEmpty(dateStr)){
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {

            return sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * date格式化
     * @param date
     * @param pattern  如  yyyy-MM-dd
     * @return
     */
    public static Date formatDateToDate(Date date,String pattern) {
        if (date == null){
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            String tempDate = sdf.format(date);
            return sdf.parse(tempDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * date转String
     * @param date  时间
     * @param pattern  格式  如：yyyy-MM-dd
     * @return
     */
    public static String formatToStr(Date date,String pattern) {
        if (date==null){
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }


    public static String dayForWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        Integer num = calendar.get(Calendar.DAY_OF_WEEK);
        String week = null;
        switch(num){
            case 1: week="周日";break;
            case 2: week="周一";break;
            case 3: week="周二";break;
            case 4: week="周三";break;
            case 5: week="周四";break;
            case 6: week="周五";break;
            case 7: week="周六";break;
            default :week=null;
        }
        return week;
    }


    public static Integer dayForWeek2(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        Integer num = calendar.get(Calendar.DAY_OF_WEEK);
        Integer week = null;
        switch(num){
            case 2: week=1;break;
            case 3: week=2;break;
            case 4: week=3;break;
            case 5: week=4;break;
            case 6: week=5;break;
            case 7: week=6;break;
            case 1: week=7;break;
            default :week=null;
        }
        return week;
    }

}
